<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<% String path=request.getContextPath(); String basePath=request.getScheme()+ "://" + request.getServerName() + ":" + request.getServerPort() + path+ "/"; %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" >
<html  xmlns="http://www.w3.org/1999/xhtml"> 
<head>
<base href="<%=basePath%>">
<title>信保通算法配置</title>
	<%@ include file="/WEB-INF/jsp/common/common.jsp" %>
	<script src="<%=path%>/js/jquery.divbox.js" type="text/javascript"></script>
	<script src="js/json2.js" type="text/javascript"></script>
	<style type="text/css">
	.inputArea{
		width:100px; 
	}
	</style>
	<script type="text/javascript">
	/* 2022年12月 取消掉产品总费率算法，改为一个单独的列 是否主险费率算法标识存到算法cond13上，0否1是 */
	//自定义map功能
	function Map(){
	  this.elements = new Array();
	   //获取MAP元素个数
	   this.size = function() {
	       return this.elements.length;
	   };
	   //判断MAP是否为空
	   this.isEmpty = function() {
	       return (this.elements.length < 1);
	   };
	   //删除MAP所有元素
	   this.clear = function() {
	       this.elements = new Array();
	   };
	   //向MAP中增加元素（key, value)
	   this.put = function(_key, _value) {
	       if(this.containsKey(_key)){
	        this.remove(_key);
	        this.elements.push( {
	           key : _key,
	           value : _value
	        });
	       }else{
	        this.elements.push( {
	           key : _key,
	           value : _value
	        });
	       }  
	   };
	   //删除指定KEY的元素，成功返回True，失败返回False
	   this.remove = function(_key) {
	       var bln = false;
	       try {
	           for (var i = 0; i < this.elements.length; i++) {
	               if (this.elements[i].key == _key) {
	                   this.elements.splice(i, 1);
	                   return true;
	               }
	           }
	       } catch (e) {
	           bln = false;
	       }
	       return bln;
	   };
	   //获取指定KEY的元素值VALUE，失败返回NULL
	   this.get = function(_key) {
	       try {
	           for (var i = 0; i < this.elements.length; i++) {
	               if (this.elements[i].key == _key) {
	                   return this.elements[i].value;
	               }
	           }
	       } catch (e) {
	           return false;
	       }
	       return false;
	   };
	   //判断MAP中是否含有指定KEY的元素
	   this.containsKey = function(_key) {
	       var bln = false;
	       try {
	           for (var i = 0; i < this.elements.length; i++) {
	               if (this.elements[i].key == _key) {
	                   bln = true;
	               }
	           }
	       } catch (e) {
	           bln = false;
	       }
	       return bln;
	   };
	  //获取map的所有values
	  this.values = function() {
	       var arr = new Array();
	       for (var i = 0; i < this.elements.length; i++) {
	           arr.push(this.elements[i].value);
	       }
	       return arr;
	   };
	  //获取map的所有keys
	  this.keys= function() {
	       var arr = new Array();
	       for (var i = 0; i < this.elements.length; i++) {
	           arr.push(this.elements[i].key);
	       }
	       return arr;
	   };
	   //获取数组
	   this.getArray= function(){
	   	var arr = new Array();
	   	for (var i = 0; i < this.elements.length; i++) {
	           arr.push({
		            key : this.elements[i].key,
		            value : this.elements[i].value
		         });
	       }
	       return arr;
	   };
	}
//********************************************	
	//险种代码
	var riskCode = "${riskCode}";
	//是否主险
	var mainRisk = riskCode.substr(0,1);
	//产品代码
	var prodCode = "${tradProdCode}";
	//责任代码
	var covId = "";
	var count1 = 0;
	var rationId = "${rationId}";
	
	//下面好多地方有用到childNode , 导致加入一列后影响到所有取值，定义一些全局变量，记录每列对应内容的位置
	//p -> position
	var p_no = 0;//序号	
	var p_rule = 1;//算法规则
	var p_deptCode = 2;//机构代码
	var p_deptName = 3;//机构名称
	var p_feeRate = 4;//费率
	var p_shortRate = 5;//短期费率
	var p_mainRiskRate = 6;//是否产品总费率
	var p_bits = 7;//小数位数
	var p_min = 8;//最小区间
	var p_max = 9;//最大区间
	var p_flag = 10;//信保通、农贷通标识
	var p_option = 11;//操作
	var p_id = 12;//id
	
	
	$(document).ready(function() {
		loadCovList();
		//初始化加载已配置的算法列表
		queryFeeRateList();
		$.closeLoading();
	})
	
function 	loadCovList(){
		var calId = "000000000877";
		var param = {prodCode:prodCode,riskCode:riskCode,calId:calId};
		$.ajax({
			url : "nlifeProductConfig/queryNlifeCovByMap",
			type : 'POST',
			async : false,
			data:param,
			dataType:'json',
			success:function(data){
				var obj = document.getElementById("covList");
				var content = "<select id = 'choseCovId' onchange='changeCov(this)'>"
				for(var i = 0 ; i < data.length ; i++){
					if(i == 0){
						covId = data[i].code;
					}
					content += "<option value='"+data[i].code+"'>"+data[i].code + " - "+data[i].name+"</option>"
				}
				content += "</select>"
				obj.innerHTML = content;
			}
		});
	}
	
	
	function changeCov(obj){
		covId = obj.value;
		queryFeeRateList();
	}
//数据导入窗体开关
function calTemplateImport(){
	$("#calTemplateImportDiv").css({"width":"50%","height":"135px"});
	$("#chooseReconciliationFileForm").css("display","block");
	$("#calTemplateImportDiv").OpenDiv3();
}
//关闭批量更新Div
function closeCalTemplateImportDiv(){
		$("#calTemplateImportDiv").CloseDiv3();
}
	
var globalCallTypeOptions='';

//查询已存在算法
function queryFeeRateList(){
	//查询条件
	var deptNameInfo = $('#deptNameInfo').val();
	var deptCodeInfo = $('#deptCodeInfo').val();
	
	//产品代码+险种代码+责任代码确定算法
	var param = {prodCode:prodCode,riskCode:riskCode,covId:covId,deptCodeInfo:deptCodeInfo,deptNameInfo:deptNameInfo,rationId:rationId};
		$.openLoading();
	
	
	$.ajax({
		url : "<%=path%>/product/feeRate/queryXBTFeeRate",
		type : 'POST',
		async : false,
		data:param,
		dataType:'json',
		success:function(map){
			//获取一个算法的list
			var calls = map.calls;
			//获取算法种类列表
			var callTypes=map.callTypes;
			//算法规则下拉菜单

			//需求类型下拉菜单:
			var XBTflagOptions = "<td><select disabled='disabled' style='background-color:lightgray'>"+"<option value='1'>信保通</option>"+"<option value='0'>农贷通</option>" + "</select></td>";
			
			//操作栏
			var options = "<td><a onclick='deletThisCal(this)'>删除</a>&nbsp&nbsp<a onclick='editThisCal(this)'>编辑</a>";
			//循环处理list， 拼成html最好
			var content = "<tbody>";
			var callTypeOptions1 = "<td><select  onchange='changeCalType(this)' >"
			//当不是主险时，不能选择主险xx算法 
				for (var k = 0; k < callTypes.length; k++) {
					if(callTypes[k].code != 8){
						callTypeOptions1 += "<option value='"+callTypes[k].code+"'>"+callTypes[k].codeName+"</option>";
					}else{
						if(mainRisk == '1'){
							callTypeOptions1 += "<option value='"+callTypes[k].code+"'>"+callTypes[k].codeName+"</option>";
						}
					}					
				}
			callTypeOptions1 +="</select></td>";
			globalCallTypeOptions = callTypeOptions1;
			for(var i = 0 ; i < calls.length;i++){
				count1 = i+1;
				//费率
				var premRate = calls[i].premRate;
				//机构代码
				var deptCode = calls[i].cond7;
				//信保通标识
				var XBTflag = calls[i].cond10;
				//算法类型
				var callType = calls[i].cond3;
				//最大区间
				var max = calls[i].cond2;
				if(max == 'null'){
					max = '';
				} 
				//最小区间
				var min = calls[i].cond1;
				if(min == 'null'){
					max = '';
				}
				//保留小数位数
				var point = calls[i].cond12;
				//是否主险总费率算法
				var isMainRiskRate = calls[i].cond13;
				//机构名称
				var deptname = calls[i].deptCname;
				if(deptname == null){
					deptname = "未定义的出单机构";
				}
				//处理为HTML：
				//初始化：
				var tableStr = "<tr>";
				//序号
				tableStr += "<td>" + count1 + "</td>";
				//算法规则select
				var callTypeOptions = "<td><select onchange='changeCalType(this)' select disabled='disabled' style='background-color:lightgray'>"
				for (var j = 0; j < callTypes.length; j++) {
					if(callType == callTypes[j].code){
							callTypeOptions += "<option value='"+callTypes[j].code+"' selected = 'selected'>"+callTypes[j].codeName+"</option>";
					}
					else{
						if(callTypes[j].code != 8){
							callTypeOptions += "<option value='"+callTypes[j].code+"'>"+callTypes[j].codeName+"</option>";
						}else {
							if(mainRisk == "1"){
								callTypeOptions += "<option value='"+callTypes[j].code+"'>"+callTypes[j].codeName+"</option>";
							}
						}
							
					} 
				}
				
				tableStr += callTypeOptions;
				//机构input
				tableStr += "<td><input class='inputArea' type='text' value='" + deptCode + "'readonly='true' style='background-color:lightgray'></td>";
				//机构名称input
				tableStr += "<td>"+deptname+"</td>";
				//费率input
				/* if(callType == '8'){
					tableStr += "<td>" + "不可编辑" + "</td>";
				}else{
					tableStr += "<td><input class='inputArea' type='text' value='" + premRate + "'readonly='true' style='background-color:lightgray'>‰</td>";
				} */
				tableStr += "<td><input class='inputArea' type='text' value='" + premRate + "'readonly='true' style='background-color:lightgray'>‰</td>";
				//20200521新增列 ， 短期费率列
				if(callType == '2' || callType =='4'){
					tableStr += "<td><a onclick='shortPremRate(this)'>编辑</a></td>";
				}else{
					tableStr += "<td>不可配置</td>";
				}
				//主险总费率input
				//改为下拉框，选择 是  / 否
				/* if(callType == '8'){
					tableStr += "<td><input class='inputArea' type='text' value='" + premRate + "' readonly='true' style='background-color:lightgray' >‰</td>";
				}else {
					tableStr +=  "<td>不可配置</td>";
				} */
				if(isMainRiskRate == '1'){
					tableStr += "<td><select style='' selected = 'selected' disabled='disabled' style='background-color:lightgray'>"+"<option value='1'>是</option>"+"<option value='0'>否</option>" + "</select></td>";
				}else {
					tableStr += "<td><select style='' disabled='disabled'>"+"<option value='1' style='background-color:lightgray'>是</option>"+"<option value='0' selected='selected'>否</option>" + "</select></td>";
				}
				//保留小数select 分初始值
				switch(point){
					case '0':
						tableStr += "<td><select disabled='disabled' style='background-color:lightgray'><option value='0' selected='selected'>0</option><option value='1'>1</option><option value='2'>2</option></select></td>";
						break;
					case '1':
						tableStr += "<td><select disabled='disabled' style='background-color:lightgray'><option value='0'>0</option><option value='1' selected='selected'>1</option><option value='2'>2</option></select></td>";
						break;
					case '2':
						tableStr += "<td><select disabled='disabled' style='background-color:lightgray'><option value='0'>0</option><option value='1'>1</option><option value='2' selected='selected'>2</option></select></td>";
						break;
					default:
						tableStr += "<td><select disabled='disabled' style='background-color:lightgray'><option value='0'>0</option><option value='1'>1</option><option value='2'>2</option></select></td>";				
				}
					
				//判断是否是整年区间费率，若是，安排大小区间
				if(callType == '3'){
					
					//最小区间
					tableStr += "<td><input type='text' style='background-color:lightgray;width:70px' value='" + min + "' readonly='true'></td>";
					//最大区间
					tableStr += "<td><input type='text' style='background-color:lightgray;width:70px' value='" + max + "' readonly='true'></td>";
					}
				else{
					//最小区间 - 只读
					tableStr += "<td><input type='text'  style='background-color:lightgray;width:70px' value='' readonly='true'></td>";
					//最大区间 - 只读
					tableStr += "<td><input type='text' style='background-color:lightgray;width:70px' value='' readonly='true'></td>";
				}
				
				//需求类型select 
				if(XBTflag == '0'){
					tableStr += "<td><select disabled='disabled' style='background-color:lightgray'>"+"<option value='1'>信保通</option>"+"<option value='0' selected='selected'>农贷通</option>" + "</select></td>";
				}else{
					tableStr += "<td><select disabled='disabled' style='background-color:lightgray'>"+"<option value='1' selected='selected'>信保通</option>"+"<option value='0'>农贷通</option>" + "</select></td>"
				}
				//操作
				tableStr += options;
				//一次循环结束
				tableStr += "<td style='display:none'>"+calls[i].id+"</td>"+"</tr>";
				content += tableStr;	
			}
			content += "</tbody>"
			var tableObj = $("#addCovDivTable");
		 	tableObj.find("tbody").remove(); 
			tableObj.append(content);
			$.closeLoading();
			return;
		}
	});
}

//添加行
function addLine(){
	$.openLoading();
	//序号 +1
	count1 += 1;
	//需求下拉菜单
	var XBTflagOptions = "<td><select>"+"<option value='1'>信保通</option>"+"<option value='0'>农贷通</option>" + "</select></td>";
	var callTypeOptions = globalCallTypeOptions;
	//操作栏
	var options = "<td><a onclick='editOverThisCal(this,true)'>完成</a>&nbsp&nbsp<a onclick=cancelThisLine(this)>删除</a></td>";
	//初始化：
	var tableStr = "<tr>";
	//序号
	tableStr += "<td>" + count1 + "</td>";
	//算法规则select
	tableStr += callTypeOptions;
	//机构input
	tableStr += "<td><input type='text' class='inputArea' value=''></td>";
	//机构名称input 只读
	tableStr += "<td><input type = 'text' readonly='true' style='background-color:lightgray'>"
	//费率input
	tableStr += "<td><input type='text' class='inputArea' value=''>‰</td>";
	//短期费率 默认不可配置
	tableStr += "<td>不可配置</td>";
	//产品总费率 默认不可配配置  改为下拉
	//tableStr += "<td>不可配置</td>";
	tableStr += "<td><select style='' selected = 'selected'>"+"<option value='1'>是</option>"+"<option value='0'>否</option>" + "</select></td>";
	//保留小数位数
	tableStr += "<td><select><option value='0'>0</option><option value='1'>1</option><option value='2' selected='selected'>2</option></select></td>";
	//最小区间 - 默认只读
	tableStr += "<td><input type='text' style='width:70px;background-color:lightgray' value=''readonly='true'></td>";
	//最大区间 - 默认只读
	tableStr += "<td><input type='text' style='width:70px;background-color:lightgray' value=''readonly='true'></td>";
	
	
	//需求类型select 
	tableStr += XBTflagOptions;
	//操作
	tableStr += options;
	//一次循环结束
	tableStr += "<td style='display:none'></td>"+"</tr>";
	var tableObj = $("#addCovDivTable");
	tableObj.append(tableStr);
	$('#deptNameInfo').val("");
	$('#deptCodeInfo').val("");
	//滚动条自动定位到底部
	var div = document.getElementById("calDDD");
	div.scrollTop = div.scrollHeight;
	$.closeLoading();
}
function cancelThisLine(obj){
	var editTr = $(obj).parent('td').parent('tr')[0];
	editTr.remove();
	count1 -= 1;
}
//删除此行
function deletThisCal(obj){
	//操作的行
	var editTr = $(obj).parent('td').parent('tr')[0];
/* 	//责任代码
	var covCode = covId;
	//机构代码cond7
	var cond7 = editTr.childNodes[2].childNodes[0].value;
	//信保通标识cond10
	var cond10 =  editTr.childNodes[8].childNodes[0].value; */
	//获取id
	var id = cond10 =  editTr.childNodes[p_id].innerHTML; 
	//拼接json
	var param = {id:id};
	$.dialog({
		type: "warn",
		content:"是否确认删除此算法?",
		onOk: function() {
			$.openLoading();
			$.ajax({
				url : "<%=path%>/product/feeRate/deletThisCal",
				type : 'POST',
				async : true,
				data:param,
				dataType:'json',
				success:function(result){
					if(result.result=='success'){
						editTr.remove();
						$.message("success","删除成功");
						return ;
					}
				}
			});
			queryFeeRateList();
			$.closeLoading();
		}
	});
	
}
//取消添加的行
function cancelThisLine(obj){
	var editTr  = $(obj).parent('td').parent('tr')[0];
	editTr.remove();
	count1 -= 1;
}

//编辑按钮 
function editThisCal(obj){
	//当编辑按钮为true ， 即将readonly的行变更为可写
	var editTr  = $(obj).parent('td').parent('tr')[0];
	editTr.childNodes[p_rule].childNodes[0].removeAttribute('disabled');
	editTr.childNodes[p_rule].childNodes[0].style.backgroundColor = 'white';
	editTr.childNodes[p_bits].childNodes[0].removeAttribute('disabled');
	editTr.childNodes[p_bits].childNodes[0].style.backgroundColor = 'white';
	editTr.childNodes[p_flag].childNodes[0].removeAttribute('disabled');
	editTr.childNodes[p_flag].childNodes[0].style.backgroundColor = 'white';
	editTr.childNodes[p_deptCode].childNodes[0].removeAttribute('readonly');
	editTr.childNodes[p_deptCode].childNodes[0].style.backgroundColor = 'white';
	editTr.childNodes[p_feeRate].childNodes[0].removeAttribute('readonly');
	editTr.childNodes[p_feeRate].childNodes[0].style.backgroundColor = 'white';
	if(editTr.childNodes[p_rule].childNodes[0].value == '3'){
		editTr.childNodes[p_min].setAttribute('readonly','false');
		editTr.childNodes[p_min].childNodes[0].style.backgroundColor = 'white';
		editTr.childNodes[p_max].setAttribute('readonly','false');
		editTr.childNodes[p_max].childNodes[0].style.backgroundColor = 'white';
	}/* else if(editTr.childNodes[p_rule].childNodes[0].value == '-1'){ //取消掉关于总费率算法的判断
		editTr.childNodes[p_mainRiskRate].childNodes[0].removeAttribute('readonly');
		editTr.childNodes[p_mainRiskRate].childNodes[0].style.backgroundColor = 'white';
	} */
	editTr.childNodes[p_mainRiskRate].childNodes[0].removeAttribute('disabled');
	editTr.childNodes[p_mainRiskRate].childNodes[0].style.backgroundColor = 'white';
	editTr.childNodes[p_option].innerHTML="<a onclick='editOverThisCal(this,true)'>完成</a>";	
}
var insertSuccess = 0;
var insertFailed = 0;
var updateSuccess = 0;
var updateFailed = 0;
//编辑完成按钮
function editOverThisCal(obj,flag){
	//新增参数flag ， 单行修改、添加为true，多行同时添加为false
	//输入置为不可用
	var editTr  = $(obj).parent('td').parent('tr')[0];
	var cond3 = editTr.childNodes[p_rule].childNodes[0].value;
	var cond7 = editTr.childNodes[p_deptCode].childNodes[0].value;
	/* if(cond3 != '-1'){//取消掉关于总费率算法的判断
		var premRate =  editTr.childNodes[p_feeRate].childNodes[0].value;	
	}else {
		var premRate =  editTr.childNodes[p_mainRiskRate].childNodes[0].value;	
	} */
	var premRate =  editTr.childNodes[p_feeRate].childNodes[0].value;
	var unused = editTr.childNodes[p_bits].childNodes[0].value;
	var cond1 = editTr.childNodes[p_min].childNodes[0].value;
	var cond2 = editTr.childNodes[p_max].childNodes[0].value;
	var cond10 = editTr.childNodes[p_flag].childNodes[0].value;
	var cond13 = editTr.childNodes[p_mainRiskRate].childNodes[0].value;
	var id = editTr.childNodes[p_id].innerHTML;
	if((premRate == ""|| cond7 == "")&& flag==true){
		$.message("error","请输入机构代码及费率信息");
		return ;
	}
	if(cond3 == '3'){	
		if((cond1 == '' || cond2 == '')){
			if(flag == true){
				$.message('error','配置整年区间税率算法需配置最大/最小区间信息！');
				return ;
			}else{
				insertFailed += 1;
				return;
			}	
		}else if(parseFloat(cond2) < parseFloat(cond1)){
			if(flag == true){
				$.message('error','最大区间不得小于最小区间！');
				return ;
			}else{
				insertFailed += 1;
				return;
			}	
		}		
	}
	editTr.childNodes[p_rule].childNodes[0].removeAttribute('disabled');
	editTr.childNodes[p_rule].childNodes[0].style.backgroundColor = 'lightgray';
	editTr.childNodes[p_bits].childNodes[0].removeAttribute('disabled');
	editTr.childNodes[p_bits].childNodes[0].style.backgroundColor = 'lightgray';
	editTr.childNodes[p_flag].childNodes[0].removeAttribute('disabled');
	editTr.childNodes[p_flag].childNodes[0].style.backgroundColor = 'lightgray';
	editTr.childNodes[p_deptCode].childNodes[0].setAttribute('readonly','false');
	editTr.childNodes[p_deptCode].childNodes[0].style.backgroundColor = 'lightgray';
	editTr.childNodes[p_feeRate].setAttribute('readonly','false');
	editTr.childNodes[p_feeRate].style.backgroundColor = 'lightgray';
	editTr.childNodes[p_min].setAttribute('readonly','true');
	editTr.childNodes[p_min].childNodes[0].style.backgroundColor = 'lightgray';
	editTr.childNodes[p_max].setAttribute('readonly','true');
	editTr.childNodes[p_max].childNodes[0].style.backgroundColor = 'lightgray';
	editTr.childNodes[p_mainRiskRate].childNodes[0].removeAttribute('disabled');
	editTr.childNodes[p_mainRiskRate].childNodes[0].style.backgroundColor = 'lightgray';
	/* if(cond3 == '8'){
		editTr.childNodes[p_mainRiskRate].setAttribute('readonly','true');
		editTr.childNodes[p_mainRiskRate].childNodes[0].style.backgroundColor = 'lightgray';
	} */
	editTr.childNodes[p_option].innerHTML="<td><a onclick='deletThisCal(this)'>删除</a>&nbsp&nbsp<a onclick='editThisCal(this)'>编辑</a>";	
	
	
	var param = {id:id,cond7:cond7,premRate:premRate,unused:unused,cond1:cond1,cond2:cond2,cond3:cond3,cond10:cond10,cond13:cond13,prodCode:prodCode,riskCode:riskCode,covCode:covId,rationId:rationId};
	//当未录入保费信息或机构代码，且是单行录入时

	
	if(id == null || id =="" ||id == undefined){
		//没有取到id，走的是insert的逻辑代码
		if((premRate == ""|| cond7 == "")){
			insertFailed += 1;
			return ;
		}
		
		//增加逻辑：选择为年区间算法时，不能单以机构代码判断重复 ， 单一机构下可以配置多条算法（判断算法的区间是否重复）
		//算法的区间不能有重叠
		$.ajax({
			url : "<%=path%>/product/feeRate/isExistCal",
			type : 'POST',
			async : false,
			data:param,
			dataType:'json',
			success:function(data){
				if(data.isExist == "true"&&flag == true){
					$.message("error","添加失败：该机构已配置算法。");
					editTr.remove();
					$.closeLoading;
					return;
				}else if(data.isExist == "true"&&flag == false){
					//当批量添加时，不弹窗，直接添加失败；
					insertFailed+= 1;

					return;
					
				}else{
				
					//未配置该机构的算法；
					param = {cond7:cond7,premRate:premRate,unused:unused,cond1:cond1,cond2:cond2,cond3:cond3,cond10:cond10,cond13:cond13,prodCode:prodCode,riskCode:riskCode,covCode:covId,rationId:rationId};
					$.ajax({
						url : "<%=path%>/product/feeRate/insertThisCal",
						type : 'POST',
						async : false,
						data:param,
						dataType:'json',
						success:function(result){
							if(flag == true){
								$.message(result.result,result.message);
								queryFeeRateList();
							}else{
								if(result.result == "success"){
									insertSuccess += 1;	
								}else{
									insertFailed += 1;
								}
							}
						}
					});
				}
				
			}
		});
	}else{
		//取到了ID 走update的方法
		if((premRate == ""|| cond7 == "")){
			updateFailed += 1;
			return ;
		}
		$.ajax({
			url : "<%=path%>/product/feeRate/updateThisCal",
			type : 'POST',
			async : false,
			data:param,
			dataType:'json',
			success:function(result){
				if(flag == true){
					$.message(result.result,result.message);
					queryFeeRateList();
				}else{
					if(result.result == "success"){
						updateSuccess += 1;	
					}else{
						updateFailed+= 1;
					}
				}
			}
		});
	}
	
}
//导入数据拼接
function getTableHtml(data) {
	var callTypes = data.callTypes;
	//定义的算法
	var calls = data.calls;
	//需求下拉菜单
	var content="";
	//操作栏
	var options = "<td><a onclick='editOverThisCal(this,true)'>完成</a>&nbsp&nbsp<a onclick=cancelThisLine(this)>删除</a></td>";
	for(var l = 0; l < calls.length ; l++){
		//初始化：
		var tableStr = "<tr>";
		count1 += 1;
		//序号
		tableStr += "<td>" + count1 + "</td>";
		//算法规则select
		var callTypeOptions = "<td><select onchange='changeCalType(this)'>"
				for (var j = 0; j < callTypes.length; j++) {
					if(data.calls[l].cond3 == callTypes[j].code){
							callTypeOptions += "<option value='"+callTypes[j].code+"' selected = 'selected'>"+callTypes[j].codeName+"</option>";
					}
					else{
						if(mainRisk != "8"){
							callTypeOptions += "<option value='"+callTypes[j].code+"'>"+callTypes[j].codeName+"</option>";
						}else {
							if(mainRisk == '1'){
								callTypeOptions += "<option value='"+callTypes[j].code+"'>"+callTypes[j].codeName+"</option>";
							}
						}
					}
				}
				callTypeOptions+="</select></td>";
		tableStr += callTypeOptions;
		//机构input
		tableStr += "<td><input type='text' class='inputArea' value='"+ data.calls[l].cond7 +"'></td>";
		//机构名称input 只读
		tableStr += "<td><input type = 'text' readonly='true'>"
		//费率input
		tableStr += "<td><input type='text' class='inputArea' value='"+data.calls[l].premRate+"'>‰</td>";
		
//		短期费率
		tableStr += "<td>保存后配置</td>";
		//主险总费率
		/* if(callTypes[j].code == '8'){
			tableStr +="<td><input class='inputArea' type='text' value='"+data.calls[l].cond8+"'style='background-color:lightgray'>‰</td>";
		}else {
			tableStr += "<td>不可配置</td>"
		} */
		tableStr += "<td><select style='' selected = 'selected'>"+"<option value='1'>是</option>"+"<option value='0'>否</option>" + "</select></td>";
		//保留小数位数
		tableStr += "<td><select><option value='0'>0</option><option value='1'>1</option><option value='2'>2</option></select></td>";
		//最小区间 - 默认只读
		var cond1;
		if(isNaN(data.calls[l].cond1)){
			cond1 = "";
		}
		else{
			cond1 = data.calls[l].cond1;
		}
		tableStr += "<td><input type='text' style='width:70px' value='"+cond1+"'readonly='true'></td>";
		//最大区间 - 默认只读
		var cond2;
		if(isNaN(data.calls[l].cond2)){
			cond2 = "";
		}else{
			cond2 = data.calls[l].cond2;
		}
		tableStr += "<td><input type='text' style='width:70px' value='"+cond2+"'readonly='true'></td>";
		
		
		//需求类型select 
		var XBTflagOptions = "<td><select>"+"<option value='1' selected='selected'>信保通</option>"+"<option value='0'>农贷通</option>" + "</select></td>";
		var NDTflagOptions = "<td><select>"+"<option value='1'>信保通</option>"+"<option value='0' selected='selected'>农贷通</option>" + "</select></td>";
		if(data.calls[l].cond10 == "1"){
			tableStr += XBTflagOptions;
		}else{
			tableStr += NDTflagOptions;
		}
		//操作
		tableStr += options;
		//一次循环结束
		tableStr += "<td style='display:none'></td>"+"</tr>";
		content += tableStr;
	}

	
		return content;
	//责任贷款金额保费算法
	
}
//导入数据
function reconciliationFileChose(){
	var reconciliationFile=$("#reconciliationFile").val();
	if(reconciliationFile.length == 0){
		$.message("error","请先选择更新文件");
		return;
	}
	if(reconciliationFile.substr(reconciliationFile.lastIndexOf(".")) != ".xls"){
		$.message("error", "必须选择xls格式的文件");
		return;
	}
	$.ajaxFileUpload({
	    url:'<%=path%>/product/feeRate/calTemplateImport1?calDefId='+'000000000877'+'&prodCode='+prodCode,  
	    fileElementId :'reconciliationFile',//file控件id
	    dataType: 'json',
	    success : function (data){
	    	if(data.result==false){
	    		$.message("error","导入失败请检查数据或联系管理员");
	        	return;
	      }else if(data.result){
	    	  closeCalTemplateImportDiv();
	    	  
	    		  var tableHtml = getTableHtml(data);
					if(tableHtml == undefined) {
						$.message("error","该险种算法配置有误，请检查数据库中对应的算法表或联系管理员");
						return;
					}
				var tableObj = $("#addCovDivTable");
				tableObj.append(tableHtml);



			$.message("success","导入成功");
            }
	    }
	});	
	
}
//下载模板
function calTemplateDownLoad(){
	window.location.href='<%=path%>/product/feeRate/newLifeDownLoad?calDefId=000000000877';
}
//判断是否是整年区间算法
function changeCalType(obj){
	
	var editTr  = $(obj).parent('td').parent('tr')[0];
	
	var callType = editTr.childNodes[p_rule].childNodes[0].value;
	if(callType == '3'){
		editTr.childNodes[p_min].childNodes[0].removeAttribute('readonly');
		editTr.childNodes[p_min].childNodes[0].style.backgroundColor = 'white';
		editTr.childNodes[p_max].childNodes[0].removeAttribute('readonly');
		editTr.childNodes[p_max].childNodes[0].style.backgroundColor = 'white';
	}else{
		editTr.childNodes[p_min].childNodes[0].setAttribute('readonly','readonly');
		editTr.childNodes[p_min].childNodes[0].style.backgroundColor = 'lightgray';
		editTr.childNodes[p_max].childNodes[0].setAttribute('readonly','readonly');
		editTr.childNodes[p_max].childNodes[0].style.backgroundColor = 'lightgray';
	}
	//当配置算法为主险总费率算法，显示改变
	/* if(callType == '-1'){//取消掉关于总费率算法的判断
		var oldNode = editTr.childNodes[p_mainRiskRate];
		var newNodeHtml ="<input class='inputArea' type='text' value='"+"'style='background-color:white'>‰";
		oldNode.innerHTML = newNodeHtml;
		oldNode = editTr.childNodes[p_feeRate];
		newNodeHtml ="不可配置";
		oldNode.innerHTML = newNodeHtml;
	}else {
		var oldNode = editTr.childNodes[p_mainRiskRate];
		var newNodeHtml ="不可配置";
		oldNode.innerHTML = newNodeHtml;
		oldNode = editTr.childNodes[p_feeRate];
		newNodeHtml ="<td><input class='inputArea' type='text' value='" + "'style='background-color:white'>‰</td>";
		oldNode.innerHTML = newNodeHtml;
	} */
	
	
	
	
}
function saveAllCal(){
	//思路：调用count1次update方法，每一行一次，如果没取到id，则insert，取到了就是update
	var tableObj = document.getElementById("addCovDivTable");
	$.openLoading();
	
	for(var i = 0; i < count1 ;i++){
		editOverThisCal(tableObj.childNodes[4].childNodes[i].childNodes[p_option].childNodes[0],false);
	}
	$.closeLoading();
	$.message("success","已完成，新增成功 " + insertSuccess +"条，失败" + insertFailed + "条");
	insertSuccess = 0;
	insertFailed = 0;
	updateSuccess= 0;
	updateFailed = 0;
	queryFeeRateList();
}

function backToProdConfig(){
	window.location.href='<%=basePath%>product/feeRate/backToProductConfig?prodCode='+prodCode;
}

function reset(){
	$("#deptNameInfo").val("");
	$("#deptCodeInfo").val("");
}

var inOperateLine ;//全局变量：正在进行短期费率调整的行对象

//点击打开编辑短期费率窗体
function shortPremRate(obj){
	inOperateLine =$(obj);
	$("#shortRateConfigDiv").css({"width":"50%","height":"235px"});
	$("#shortRateConfigForm").css("display","block");
	$("#shortRateConfigDiv").OpenDiv3();
	//获取机构代码
	var deptCode = inOperateLine.parent('td').parent('tr')[0].childNodes[p_deptCode].childNodes[0].value;
	//获取信保通标识
	var xbtFlag = inOperateLine.parent('td').parent('tr')[0].childNodes[p_flag].childNodes[0].value;
	
	var param = {prodCode:prodCode,riskCode:riskCode,covCode:covId,deptCode:deptCode,xbtFlag:xbtFlag}
	
	//数据回写
	$.openLoading();
	$.ajax({
		url : "<%=path%>/product/feeRate/writeBackShortRate",
		type : 'POST',
		async : false,
		data:param,
		dataType:'json',
		success:function(result){
			$.closeLoading();
			console.log(result.result == "success");
			if(result.result == "success"){
				var shortRates = result.data;
				var monthArray = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
				for(month in monthArray){
					document.getElementById(monthArray[month]).value = shortRates[month];
				}
				
			}
			
		}
	});
	
}



//关闭/取消编辑短期费率窗体
function closeShortRateConfigDiv(){
	$("#shortRateConfigDiv").CloseDiv3();
	var monthArray = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
	for(month in monthArray){
		document.getElementById(monthArray[month]).value = "";
	}
}

//短期费率保存
function saveShortRate(){
	//定义数组，对应各月数
	var monthArray = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
	//定义字符串吧，存短期费率信息
	var shortRateReslutStr = "";
	for(var id in monthArray){
		var shortRateStr = document.getElementById(monthArray[id]).value;
		shortRateReslutStr += shortRateStr;
		if(id < (monthArray.length - 1)){
			shortRateReslutStr += "|";
		}
	}
	//获取机构代码
	var deptCode = inOperateLine.parent('td').parent('tr')[0].childNodes[p_deptCode].childNodes[0].value;
	//获取信保通标志
	var xbtFlag = inOperateLine.parent('td').parent('tr')[0].childNodes[p_flag].childNodes[0].value;

	var param = {prodCode:prodCode,riskCode:riskCode,deptCode:deptCode,shortRate:shortRateReslutStr,covCode:covId,xbtFlag:xbtFlag,rationId:rationId}
	//进行Ajax请求  ， 存库
	$.ajax({
		url : "<%=path%>/product/feeRate/insertOrUpdateShortRate",
		type : 'POST',
		//是否异步
		async : false,
		data:param,
		dataType:'json',
		success:function(result){
				if(result.result == "success"){
					$.message(result.result,result.message);
					closeShortRateConfigDiv();
				}else{
					$.message(result.result,result.message);
				}
			}
	});
		
}
//检测输入内容
function checkShortRateFunction(obj){
	var operateInput = $(obj);
	var str = obj.value;
	if( isNaN(str) || str > 1 || str < 0){
		obj.value = "";
		$.message("warn","仅可输入0 - 1范围内的数字");
	}
}
	</script>
</head>
<body >
<!-- 定位div -->
	<div >
           <table class="current_table_1">
              <tbody>
                <tr class="f2">
                  <td>
                    <img src="./images/current_1.jpg">
                  </td>
                  <td class="current_table_1_td">
                    <img src="images/current_1.png">&nbsp;您现在的位置：&nbsp;
                      <span style=" color:#136bab; ">新意健险产品管理
                      <span style="padding:0 5px; font-weight:bold; line-height:28px;">&gt;</span><a onclick="backToProdConfig()">产品配置</a>
                      <span style="padding:0 5px; font-weight:bold; line-height:28px;">&gt;</span><a onclick="javascript:history.back()">条款添加</a>
                      <span style="padding:0 5px; font-weight:bold; line-height:28px;">&gt;</span>算法配置
                  </span>
                  </td>
                  <td><img src="./images/current_3.jpg"></td>
              </tr>
           </tbody>
         </table>
      </div>
      
      <!-- 抬头Div -->
      <div>
			<form id="inputForm" >
				<table class="table_05" style="margin:3px;">
	              <tbody>
		    		  <tr>
 		              	<td style="line-height:23px;">
 		              		<font color="#3876bf"><b>责任选择：</b><b id = "covList"></b></font> 
 		              	</td>
		              </tr>
	           	  </tbody>
	        	 </table>
	  </div>
	  
	  <!-- 搜索DIV -->
	  <div>
			<form>
				<table class="table_20">
				<thead>
					<tr class='f1' style="text-align: left;">
						<th style="text-align: left;"> &nbsp信保通算法配置</th>
					</tr>
				</thead>
	              <tbody>
		    		  <tr color="#3876bf">
		    		  	<td style='text-align:center'>
 		              		机构代码：<input id='deptCodeInfo' type="text">&nbsp&nbsp&nbsp&nbsp机构名称：<input id='deptNameInfo' type="text">
 		              		&nbsp&nbsp<input type="button" class='input_button_2' value="查询" onclick='queryFeeRateList()'>&nbsp<input type="button" class='input_button_2' value="重置" onclick='reset()'>
		              	</td>
		              </tr>
	           	  </tbody>
	        	 </table>
	         </form>
	  </div>
	  
	  
	  <!-- 主表格体div -->
	  <div style="width:100%;">
			<form id="calForm">
				<div id="calDDD" style="width:100%;overflow:auto;height: 450px;overflow-y:scroll   ;" >
					<table id="addCovDivTable" class="table_20" align="center">
					<thead>
						<tr class="f1">
								<th style="width:2%">序号</th>
								<th style="width:1%">算法规则</th>
								<th style="width:1%">机构代码</th>
								<th>机构名称</th>
								<th style="width:2%">费率（‰）</th>
								<th style="width:2%">短期费率（‰）</th>
								<th style="width:3%">是否产品总费率算法</th>
								<th style="width:3%">保留小数位数</th>
								<th style="width:1%">最小区间</th>
								<th style="width:1%">最大区间</th>
								<th style="width:2%">需求类型</th>
								<th style="width:5%">操作</th>
						</tr>
					</thead>
						<tbody>
						</tbody>
					</table>
				</div>
				
				<div align="center" id="button2">
				<table style="width:100%;">
						<tr>
							<td width="40%">
								&nbsp;&nbsp;<input class="input_button_2" name="" type="button" onclick="calTemplateDownLoad()" value="模板下载">
								&nbsp;<input class="input_button_2" name="" type="button" onclick="calTemplateImport()" value="数据导入">
							</td>
							<td width="60%">
								<input class="input_button_3" name="" type="button" onclick="saveAllCal()" value="保存">&nbsp;&nbsp;
			        			<input class="input_button_2" name="" type="button" onclick="addLine()" value="添加行">&nbsp;&nbsp;
							</td>
						</tr>
					</table>				
					</div>
			</form>
		</div>
		
		<!-- 导入算法div -->
		<div id="calTemplateImportDiv"  style="display:none;width:50%;height: 30%;background-color:#f6f7f9;">
        	<div class="table_title_div">
				<table class="table_title" style="width:100% ;height: 20px;">
					<tr>
						<td width="10%"></td>
						<td width="80%" id="interfaceName"></td>
						<td width="10%" align="right"><img src="<%=path%>/images/closedown.gif" alt="关闭"  onclick="closeCalTemplateImportDiv()"/></td>
					</tr>
				</table>
			</div>
			<!-- 批量更新文档 -->
	   		<form id="chooseReconciliationFileForm" action="" method="POST" enctype="multipart/form-data" >
	     		<table class="table_02" style="width: 92%" align="center">
	     			<tr>
	     				<td style="padding:25px 20px ">
	     					请选择批量更新文件：<input type="file" id="reconciliationFile" name="reconciliationFile"/>
	        				<input type="button" class="input_button_1" value="导入" onClick="reconciliationFileChose()"/>
	     				</td>
	     			</tr>
	     		</table>
	     	</form>     	
        </div>
        <!-- 短期费率配置 -->
		<div id="shortRateConfigDiv"  style="display:none;width:50%;height:235px;background-color:#f6f7f9;">
        	<div class="table_title_div">
				<table class="table_title" style="width:100% ;height: 20px;">
					<tr>
						<td width="10%"></td>
						<td width="80%" id="interfaceName"></td>
						<td width="10%" align="right"><img src="<%=path%>/images/closedown.gif" alt="关闭"  onclick="closeShortRateConfigDiv()"/></td>
					</tr>
				</table>
			</div>
			<!-- 需要配置某个机构，12个月的短期费率 ， 数据格式为 0.xx 即1为最大值 -->
			<!-- id是用一到十二月命名。 实际含义应当为“超过整数年的x个月” -->
	     		<table class="table_02" style="width: 92%" align="center" id="shortRateTable">
	     			<tr>
	     				<td>1月：<input id="Jan" type="text" onchange="checkShortRateFunction(this)"></td>
	     				<td>2月：<input id="Feb" type="text" onchange="checkShortRateFunction(this)"></td>
	     				<td>3月：<input id="Mar" type="text" onchange="checkShortRateFunction(this)"></td>
	     				<td>4月：<input id="Apr" type="text" onchange="checkShortRateFunction(this)"></td>
	     			</tr>
	     			<tr>
	     				<td>5月：<input id="May" type="text" onchange="checkShortRateFunction(this)"></td>
	     				<td>6月：<input id="Jun" type="text" onchange="checkShortRateFunction(this)"></td>
	     				<td>7月：<input id="Jul" type="text" onchange="checkShortRateFunction(this)"></td>
	     				<td>8月：<input id="Aug" type="text" onchange="checkShortRateFunction(this)"></td>
	     			</tr>
	     			<tr> 
	     				<td>9月：<input id="Sep" type="text" onchange="checkShortRateFunction(this)"></td>
	     				<td>10月：<input id="Oct" type="text" onchange="checkShortRateFunction(this)"></td>
	     				<td>11月：<input id="Nov" type="text" onchange="checkShortRateFunction(this)"></td>
	     				<td>12月：<input id="Dec" type="text" onchange="checkShortRateFunction(this)"></td>
	     			</tr>		
	     		</table>
	     		
	     		<table style="width: 50%"></table>
	     		<div align="center" id="button2">
				<table style="width:100%;">
						<tr>
							<td width="60%" align="center">
								<input class="input_button_3" name="" type="button" onclick="saveShortRate()" value="保存">&nbsp;&nbsp;
			        			<input class="input_button_2" name="" type="button" onclick="closeShortRateConfigDiv()" value="取消">&nbsp;&nbsp;
							</td>
						</tr>
					</table>				
					</div>
        </div>
		
</body>
</html>